package mv.crawler;

import com.google.gdata.client.GoogleService;
import com.google.gdata.data.Category;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Feed;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.data.OutOfLineContent;
import com.google.gdata.data.TextContent;
import mv.io.BluetoothIO;
import mv.io.FileIO;
import mv.io.SimpleProperties;
import mv.wap.Page;
import mv.wap.Paragraph;

import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Class description...
 *
 * @author mvu
 */
public class NotebookCrawler extends GoogleCrawler {
  private GoogleService _myService;

  public List<Page> crawl() throws Exception {
    URL allNotebooks = new URL("http://www.google.com/notebook/feeds/05365436891260101842");
    _myService = new GoogleService("notebook", "example");
    _myService.setUserCredentials(SimpleProperties.getUsername(), SimpleProperties.getPassword());
    long lastUpdated = SimpleProperties.getNotebookLastUpdated();
    Feed allNotes = _myService.getFeed(allNotebooks, Feed.class);
    List<Page> pages = new ArrayList<Page>();
    for (Entry entry : allNotes.getEntries()) {
      if (entry.getUpdated().getValue() > lastUpdated) {
        Page singleNote = getSingleNoteBook(entry);
        pages.add(singleNote);
      }
    }
    return pages;
  }

  private Page getSingleNoteBook(Entry singleNote) throws Exception {
    String title = singleNote.getTitle().getPlainText();
    String uri = ((OutOfLineContent) singleNote.getContent()).getUri();
    URL singleNotebook = new URL(uri);
    Feed noteBookFeed = _myService.getFeed(singleNotebook, Feed.class);
    Page page = new Page(title);
    for (Entry note : noteBookFeed.getEntries()) {
      //String section = getSection(note);
      //sections.get(section).add(note);
      TextContent textContent = (TextContent) note.getContent();
      String content = ((HtmlTextConstruct) textContent.getContent()).getHtml();
      page.addElement(new Paragraph(content));
    }
    return page;
  }

  private String getSection(Entry note) {
    Iterator<Category> iterator = note.getCategories().iterator();
    if(iterator.hasNext()){
      return iterator.next().getLabel();
    }else{
      return "Main";
    }
  }

  public static void main(String[] args) throws Exception {
    List<Page> pages = new NotebookCrawler().crawl();
    FileIO.getInstance().save(pages);
    BluetoothIO.main(new String[0]);
  }
}
